<!-- src/views/booking/BookingSchedule.vue -->
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import dayjs from 'dayjs'
import type { Booking } from './types'

// —— 50 条会议主题 ——
const topics = [
  '大模型时代下的数据质量管理与隐私保护创新',
  '多模态数据资产统一治理平台架构实践',
  '金融级数据标准与AI驱动的元数据管理',
  '血缘分析技术在数据溯源中的突破与应用110',
  '非结构化数据（文本/图像/视频）的智能治理方法论1',
  '数据安全合规框架与跨境流通解决方案37',
  '基于区块链的数据确权与可信共享实践',
  '数据治理成熟度评估模型与行业对标',
  '超大规模实时数仓的演进路径与性能优化110',
  'Flink与Spark Structured Streaming的实战对比',
  '毫秒级延迟的金融实时风控系统架构',
  '流批一体在电商场景的成本治理实践1',
  '物联网时序数据的高并发处理技术',
  '实时数据湖与增量计算引擎设计',
  '流式数据质量监测的动态规则引擎',
  'LLM重构数据开发：自动SQL生成与优化110',
  '大模型驱动的智能运维异常诊断体系10',
  '企业专属Agent的知识库构建与调试策略1',
  '多模态大模型在非表格数据管理中的应用1',
  '向量数据库与AI生态的集成实践10',
  '大模型与湖仓一体架构的协同优化1',
  '低代码+AI的数据分析平民化路径',
  '数据资产入表操作指南与财务实践4',
  '公共数据授权运营的合规模式探索58',
  '工业可信数据空间构建与产业链协同9',
  '数据交易所的定价机制与流动性提升',
  '“数据要素×”三年行动计划行业样板解析4',
  '数据经纪人（数商）生态角色与价值创新4',
  '跨境数据流动的沙盒监管与国际协作7',
  '保险行业数据中台智能服务化实践110',
  '智能网联汽车数据闭环与高价值数据集建设9',
  '医疗AI多中心研究的数据联邦学习方案',
  '制造业全连接工厂的数据价值释放路径9',
  '金融行业国产分布式数据库选型与改造10',
  '智慧城市时空信息平台与北斗融合应用6',
  '零售业消费者全域数据画像与实时营销',
  '多云异构数据平台的统一管控技术110',
  '云原生数据仓库的存算分离与弹性扩展',
  'Serverless化大数据作业调度实践',
  '基于Data Mesh的分布式数据资产架构',
  '超融合数据库的性能瓶颈与突破路径10',
  '绿色数据中心：算力与能效的平衡设计',
  '量子计算对大数据加密体系的冲击与应对',
  '神经符号系统在复杂推理场景的数据应用',
  '生物计算与基因数据的高效分析平台2',
  '数字孪生与实时仿真数据引擎构建9',
  'Web3.0去中心化数据存储经济模型',
  '环境科学中的函数式数据分析（如全球变暖模型）6',
  '隐私增强计算（PEC）的工程化落地',
  '认知智能时代的数据-知识-决策联动框架'
]

// 生成30个统一命名的会议室
const allRooms: string[] = Array.from({length: 30}, (_, i) => {
  const buildingIndex = i % 7;
  const building = String.fromCharCode(65 + buildingIndex); // A-G
  const floor = Math.floor(i / 7) + 1;
  const roomNum = 100 + (i % 20);
  return `${building}区${building}${floor}号楼${roomNum}`;
});

// 修复：确保生成模拟数据时使用统一格式
function generateMockBookings(): Booking[] {
  const rooms = allRooms;
  const list: Booking[] = []
  let cursor = dayjs('2025-04-01')
  const end   = dayjs('2025-07-15')
  while (cursor.isBefore(end) || cursor.isSame(end, 'day')) {
    const wd = cursor.day();
    if (wd >= 1 && wd <= 5) {
      const cnt = Math.floor(Math.random() * 3);
      for (let i = 0; i < cnt; i++) {
        const room = rooms[Math.floor(Math.random() * rooms.length)];
        const topic = topics[Math.floor(Math.random() * topics.length)];
        const hour = 9 + Math.floor(Math.random() * 8);
        const minute = [0, 15, 30, 45][Math.floor(Math.random() * 4)];
        const start = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
        const endTime = dayjs(`${cursor.format('YYYY-MM-DD')}T${start}`)
            .add(30 + 15 * Math.floor(Math.random() * 4), 'minute')
            .format('HH:mm');
        list.push({
          room,
          date: cursor.format('YYYY-MM-DD'),
          startTime: start,
          endTime: endTime,
          purpose: topic,
          status: [1, 2, 3][Math.floor(Math.random() * 3)]
        });
      }
    }
    cursor = cursor.add(1, 'day');
  }
  return list
}

const selectedRoom    = ref<string>('')
const bookings        = ref<Booking[]>([])
const calendarDate    = ref(dayjs('2025-04-01'))
const popoverVisible  = ref<Record<string,boolean>>({})

function fetchAllBookings() {
  bookings.value = generateMockBookings()
  popoverVisible.value = {}
}
onMounted(fetchAllBookings)

const filteredList = computed(() =>
    selectedRoom.value
        ? bookings.value.filter(b => b.room === selectedRoom.value)
        : bookings.value
)

const dayEvents = computed<Record<string,Booking[]>>(() => {
  const m: Record<string,Booking[]> = {}
  filteredList.value.forEach(b => (m[b.date] ||= []).push(b))
  return m
})

const roomOptions = computed(() =>
    Array.from(new Set(bookings.value.map(b => b.room)))
        .sort((a,b) => {
          const [,la,na] = a.match(/^([A-Z])区(\d+)$/)!
          const [,lb,nb] = b.match(/^([A-Z])区(\d+)$/)!
          if (la !== lb) return la.charCodeAt(0)-lb.charCodeAt(0)
          return +na - +nb
        })
)

const weekDays = ['日','一','二','三','四','五','六']
const calendarGrid = computed(() => {
  const first  = calendarDate.value.startOf('month')
  const offset = first.day()
  let cursor = first.subtract(offset,'day')
  const weeks: dayjs.Dayjs[][] = []
  for (let w=0; w<6; w++){
    const row: dayjs.Dayjs[] = []
    for (let d=0; d<7; d++){
      row.push(cursor)
      cursor = cursor.add(1,'day')
    }
    weeks.push(row)
  }
  return weeks
})

function prevMonth() { calendarDate.value = calendarDate.value.subtract(1,'month') }
function nextMonth() { calendarDate.value = calendarDate.value.add(1,'month') }
function goToday()   { calendarDate.value = dayjs() }

const currentMonthEvents = computed(() =>
    filteredList.value.filter(b =>
        dayjs(b.date).year() === calendarDate.value.year() &&
        dayjs(b.date).month() === calendarDate.value.month()
    )
)

function formatDay(d: dayjs.Dayjs) { return d.format('YYYY-MM-DD') }

function statusColor(s: number) {
  return s === 2 ? 'success' : s === 3 ? 'danger' : 'warning'
}
</script>

<template>
  <el-card class="box-card">
    <div class="container">
      <!-- 左侧：筛选 + 日历 -->
      <div class="left-pane">
        <div class="toolbar">
          <el-select
              v-model="selectedRoom"
              placeholder="请选择会议室"
              clearable
              class="select-room"
          >
            <el-option
                v-for="r in roomOptions"
                :key="r"
                :label="r"
                :value="r"
            />
          </el-select>
          <el-button type="primary" @click="fetchAllBookings">查询</el-button>
          <div class="nav-group">
            <el-button size="mini" @click="prevMonth">上个月</el-button>
            <el-button size="mini" @click="goToday">今天</el-button>
            <el-button size="mini" @click="nextMonth">下个月</el-button>
          </div>
        </div>

        <div class="month-title">{{ calendarDate.format('YYYY年M月') }}</div>

        <table class="calendar-table">
          <thead>
          <tr>
            <th v-for="wd in weekDays" :key="wd">{{ wd }}</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(week, wi) in calendarGrid" :key="wi">
            <td
                v-for="day in week"
                :key="day.toString()"
                :class="{ 'other-month': day.month() !== calendarDate.month() }"
            >
              <el-popover
                  trigger="click"
                  placement="top"
                  :width="220"
                  v-model="popoverVisible[ formatDay(day) ]"
              >
                <template #reference>
                  <div class="popover-ref">
                    <div class="date-number">{{ day.date() }}</div>
                    <div v-if="dayEvents[formatDay(day)]">
                        <span
                            v-for="(_, i) in dayEvents[formatDay(day)].length"
                            :key="i"
                            class="dot"
                        />
                    </div>
                  </div>
                </template>

                <div v-if="dayEvents[formatDay(day)]?.length">
                  <el-card
                      v-for="e in dayEvents[formatDay(day)]"
                      :key="e.room + e.startTime"
                      shadow="never"
                      class="day-popover-card"
                  >
                    <div class="pop-room">会议室：{{ e.room }}</div>
                    <div class="pop-time">{{ e.startTime }} - {{ e.endTime }}</div>
                    <div class="pop-purpose">{{ e.purpose }}</div>
                  </el-card>
                </div>
                <div v-else class="no-meeting">当天无会议</div>
              </el-popover>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 右侧：当月详情 -->
      <div class="right-pane">
        <div class="detail-title">
          会议详情 ({{ currentMonthEvents.length }} 条)
        </div>
        <el-scrollbar class="detail-scroll" v-if="currentMonthEvents.length > 0">
          <el-card
              v-for="evt in currentMonthEvents"
              :key="evt.date + evt.startTime + evt.room"
              shadow="hover"
              class="detail-card"
          >
            <div class="item-date">{{ evt.date }}</div>
            <el-tag :type="statusColor(evt.status)" class="tag-room">
              {{ evt.room }}
            </el-tag>
            <el-tag type="primary" class="tag-time">
              {{ evt.startTime }} - {{ evt.endTime }}
            </el-tag>
            <div class="tag-purpose">{{ evt.purpose }}</div>
          </el-card>
        </el-scrollbar>
        <div v-else class="no-meeting-prompt">
          当前月份没有会议安排
        </div>
      </div>
    </div>
  </el-card>
</template>

<style scoped>
.no-meeting-prompt {
  padding: 20px;
  text-align: center;
  color: #888;
  font-size: 14px;
}

.box-card { padding:0 }
.container { display:flex; height:calc(100vh - 120px); }
.left-pane { flex:3; background:#fff; display:flex; flex-direction:column; }
.right-pane { flex:1; background:#fff; display:flex; flex-direction:column; border-left:1px solid #eee; min-height: 100%; }

.toolbar { padding:12px; display:flex; align-items:center; }
.select-room { width:200px; }
.nav-group { margin-left:auto; display:flex; }
.nav-group .el-button + .el-button { margin-left:8px; }

.month-title { padding:0 12px; font-weight:bold; }

.calendar-table {
  width:100%; border-collapse:collapse; flex:1; cursor:pointer;
}
.calendar-table th, .calendar-table td {
  border:1px solid #eee; vertical-align:top; height:80px; padding:4px;
}
.calendar-table th { background:#fafafa; text-align:center; }
.other-month { color:#bbb; }
.date-number { font-weight:bold; }
.popover-ref { user-select:none; }
.dot {
  display:inline-block; width:6px; height:6px;
  background:#409EFF; border-radius:50%;
  margin-right:2px; margin-top:2px;
}

/* 弹框中的单条会议 */
.day-popover-card {
  margin-bottom:8px;
  padding:8px 12px;
  background:#fff;
  border-radius:4px;
  box-shadow:0 2px 6px rgba(0,0,0,0.1);
}
.pop-room {
  font-size:13px;
  color:#666;
  margin-bottom:4px;
}
.pop-time {
  font-weight:bold;
  color:#409EFF;
  margin-bottom:4px;
}
.pop-purpose {
  font-size:13px;
  color:#333;
  line-height:1.4;
  max-height:2.8em;
  overflow:hidden;
}
.no-meeting { color:#888; text-align:center; padding:12px 0; }

/* 右侧详情 */
.detail-title { padding:12px; font-weight:bold; }
.detail-scroll { flex:1; padding:8px; height: 0;}
.detail-card {
  margin-bottom:12px;
  background:#f9f9ff;
  border:1px solid #eee;
  padding:12px;
  border-radius:4px;
}
.item-date { font-weight:bold; margin-bottom:6px; }
.tag-room { margin-right:6px; }
.tag-time { }
.tag-purpose { margin-top:8px; color:#555; }
</style>
